﻿#region Header

/*
Behavioral Rating of Dancing Human Crowds based on Motion Patterns
By

Pascal Hauser 
Dipl. Ing. in Informatik, Hochschule für Technik Rapperswil, 2006
Master Thesis, Hochschule für Technik Rapperswil, 2008-2010

and

Raphael Gfeller
Dipl. Ing. in Informatik, Hochschule für Technik Rapperswil, 2006
Master Thesis, Hochschule für Technik Rapperswil, 2008-2010

*/

#endregion

#region Usings

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using Sebarf.Services.Interfaces;

#endregion

namespace paravili.Services {
	/// <summary>
	/// Description of the class
	/// </summary>
	public class DoMatchingWithLPLService : Service, IDoMatchingService {
		#region Public Properties

		// public Properties located here

		#endregion

		#region Public Methods

		// public methods located here

		#endregion

		#region Private Methods

		// private methods located here

		#endregion

		#region Private Fields

		// private fields located here

		#endregion

		#region IDoMatchingService Members

		public Match[] FindMatch(int[,] data) {
			var dataToWrite = new StringBuilder();
			dataToWrite.Append("__matrixSize");
			dataToWrite.AppendLine();
			dataToWrite.Append(data.GetLength(0));
			dataToWrite.AppendLine();
			dataToWrite.Append("__matrixSize");
			dataToWrite.AppendLine();
			dataToWrite.Append("__data");
			dataToWrite.AppendLine();
			// prepare data
			for (int i = 0; i < data.GetLength(0); i++) {
				for (int j = 0; j < data.GetLength(1); j++) {
					dataToWrite.Append(data[i, j]);
					dataToWrite.Append(" ");
				}
				dataToWrite.AppendLine();
			}
			dataToWrite.Append("__data");
			string path = Directory.GetCurrentDirectory() + "\\data.txt";
			// write data
			File.WriteAllText(path, dataToWrite.ToString());
			//			StatisticValuesProviderService.SetValueToShow("Movements.Found", toReturn.Count);

			// execute solver
			var p = new Process();
			p.StartInfo = new ProcessStartInfo("lplc.exe", "Movement.lpl");
			p.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
			p.Start();
			p.WaitForExit();

			// read result
			var toReturn = new List<Match>();
			string solution = Directory.GetCurrentDirectory() + "\\Movement.nom";
			string[] content = File.ReadAllLines(solution);
			foreach (string match in content) {
				string[] args = match.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
				int firstClusterIndex = int.Parse(args[0]) - 1;
				int lastClusterIndex = int.Parse(args[1]) - 1;
				toReturn.Add(new Match { FromIndex = firstClusterIndex, ToIndex = lastClusterIndex });
			}
			return toReturn.ToArray();
		}

		#endregion
	}
}